<template>
  <div class="map-viewer">
    <el-dialog
      :title="`站点位置 - ${stationInfo.stationName}`"
      :visible.sync="visible"
      width="800px"
      append-to-body
      @open="onDialogOpen"
      @close="onDialogClose">

      <div class="station-info-card">
        <el-card shadow="never">
          <div class="station-details">
            <div class="detail-item">
              <i class="el-icon-location-outline"></i>
              <span class="label">站点名称：</span>
              <span class="value">{{ stationInfo.stationName || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-postcard"></i>
              <span class="label">站点编码：</span>
              <span class="value">{{ stationInfo.stationCode || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-house"></i>
              <span class="label">详细地址：</span>
              <span class="value">{{ stationInfo.address || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-coordinate"></i>
              <span class="label">坐标位置：</span>
              <span class="value">{{ formatCoordinates() }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <div class="map-container">
        <div id="amap-container" class="amap-wrapper">
          <div class="map-loading" v-if="mapLoading">
            <i class="el-icon-loading"></i>
            <span>地图加载中...</span>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">关 闭</el-button>
        <el-button type="primary" @click="openInAMap" v-if="hasValidCoordinates">
          <i class="el-icon-position"></i>
          在高德地图中打开
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MapViewer',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    stationInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      visible: false,
      map: null,
      marker: null,
      mapLoading: false
    }
  },
  computed: {
    hasValidCoordinates() {
      return this.stationInfo.latitude && this.stationInfo.longitude &&
        this.stationInfo.latitude != 0 && this.stationInfo.longitude != 0
    }
  },
  watch: {
    show(val) {
      this.visible = val
      if (!val) {
        this.$emit('update:show', false)
      }
    },
    visible(val) {
      if (!val) {
        this.$emit('update:show', false)
      }
    }
  },
  methods: {
    onDialogOpen() {
      this.$nextTick(() => {
        this.initMap()
      })
    },

    onDialogClose() {
      if (this.map) {
        this.map.destroy()
        this.map = null
        this.marker = null
      }
    },

    async initMap() {
      if (!this.hasValidCoordinates) {
        this.$message.warning('该站点暂无有效的GPS坐标信息')
        return
      }

      this.mapLoading = true

      try {
        // 动态加载高德地图API
        if (!window.AMap) {
          await this.loadAmapScript()
        }

        const lat = parseFloat(this.stationInfo.latitude)
        const lng = parseFloat(this.stationInfo.longitude)

        // 创建地图实例
        this.map = new window.AMap.Map('amap-container', {
          zoom: 16,
          center: [lng, lat],
          mapStyle: 'amap://styles/normal'
        })

        // 添加站点标记
        this.marker = new window.AMap.Marker({
          position: [lng, lat],
          title: this.stationInfo.stationName,
          icon: new window.AMap.Icon({
            size: new window.AMap.Size(32, 32),
            image: 'data:image/svg+xml;base64,' + btoa(`
              <svg width="32" height="32" xmlns="http://www.w3.org/2000/svg">
                <circle cx="16" cy="16" r="12" fill="#409EFF" stroke="#fff" stroke-width="2"/>
                <circle cx="16" cy="16" r="4" fill="#fff"/>
              </svg>
            `),
            imageSize: new window.AMap.Size(32, 32)
          })
        })

        this.map.add(this.marker)

        // 添加信息窗口
        const infoWindow = new window.AMap.InfoWindow({
          content: `
            <div style="padding: 10px;">
              <div style="font-weight: bold; color: #303133; margin-bottom: 5px;">
                ${this.stationInfo.stationName}
              </div>
              <div style="color: #606266; font-size: 12px;">
                ${this.stationInfo.address || '暂无详细地址'}
              </div>
            </div>
          `
        })

        this.marker.on('click', () => {
          infoWindow.open(this.map, this.marker.getPosition())
        })

        // 地图加载完成后自动显示信息窗口
        setTimeout(() => {
          infoWindow.open(this.map, this.marker.getPosition())
        }, 500)

      } catch (error) {
        console.error('地图初始化失败:', error)
        this.$message.error('地图加载失败，请检查网络连接')
      } finally {
        this.mapLoading = false
      }
    },

    loadAmapScript() {
      return new Promise((resolve, reject) => {
        // 检查是否已经加载
        if (window.AMap) {
          resolve()
          return
        }

        const script = document.createElement('script')
        script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=您的高德地图API密钥&plugin=AMap.InfoWindow'
        script.onload = resolve
        script.onerror = reject
        document.head.appendChild(script)
      })
    },

    formatCoordinates() {
      if (this.hasValidCoordinates) {
        return `${this.stationInfo.latitude}, ${this.stationInfo.longitude}`
      }
      return '暂无坐标信息'
    },

    openInAMap() {
      if (this.hasValidCoordinates) {
        const url = `https://uri.amap.com/marker?position=${this.stationInfo.longitude},${this.stationInfo.latitude}&name=${encodeURIComponent(this.stationInfo.stationName)}`
        window.open(url, '_blank')
      }
    }
  }
}
</script>

<style scoped>
.station-info-card {
  margin-bottom: 15px;
}

.station-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.detail-item i {
  margin-right: 8px;
  color: #409eff;
  width: 16px;
}

.label {
  color: #606266;
  margin-right: 8px;
  min-width: 70px;
}

.value {
  color: #303133;
  font-weight: 500;
}

.map-container {
  position: relative;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.amap-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #606266;
  z-index: 10;
}

.map-loading i {
  font-size: 24px;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .station-details {
    grid-template-columns: 1fr;
  }

  .map-container {
    height: 300px;
  }
}

/* 高德地图样式覆盖 */
::v-deep .amap-copyright {
  display: none !important;
}

::v-deep .amap-logo {
  display: none !important;
}
</style>